<?php
class Sb_View
{
    const ROOT_VIEW = 'Sb\Html\\';

    private static $_instance;

    private $_http;

    private $controllerName;
    private $actionName;
    private $layoutName;
    
    private $disableView;

    public static function getInstance()
    {
        if(self::$_instance === null){
            self::$_instance = new self();
        }
        
        return self::$_instance;
    }
    
    public function setDisableView($disableView)
    {
    	$this->disableView = (bool)$disableView;
    	return $this;
    }

    private function __construct()
    {
        $this->_http = Sb_Http::getInstance();
        $this->initParams();
    }

    private function initParams()
    {
    	$this->disableView = false;
        $this->controllerName = $this->_http->getControllerName();
        $this->actionName = $this->_http->getActionName();
        $this->layoutName = $this->_http->getLayoutName();
    }

    private function setPageContent()
    {
        $filePath = self::ROOT_VIEW.'View\\'.$this->layoutName.'\\'.$this->controllerName.'\\'.$this->actionName.'.phtml';
        if(!file_exists($filePath)){
            $filePath = self::ROOT_VIEW.'View\Error\error.phtml';
        }
        ob_start();
        require_once $filePath;
        $partialHtml = ob_get_contents();
        ob_get_clean();
        $this->pageContent = $partialHtml;
    }

    private function isXmlHttpRequest()
    {
    	return array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
    }
    
    public function render()
    {
    	if($this->disableView){
    		return;
    	}
        $this->setPageContent();
        if(!$this->isXmlHttpRequest()){
        	require_once self::ROOT_VIEW.'Layout\\'.strtolower($this->layoutName).'.phtml';
        }else{
        	echo $this->pageContent;
        }
    }

    public function url(array $params)
    {
    	$params['ctrl'] = isset($params['ctrl']) ? $params['ctrl']: $this->controllerName;
    	$params['act'] = isset($params['act']) ? $params['act']: $this->actionName;
        $url = $params['ctrl'].'/'.$params['act'];
        foreach ($params as $k => $v){
        	if(in_array($k, array('ctrl', 'act'))){
        		continue;
        	}
        	$url .= '/'.$k.'/'.$v;
        }
        return $_SERVER['SCRIPT_NAME'].'?'.$url;
    }
}